<template>
	<view class="login-page">
		<!-- 		<image :src="codeSrc.backgroundImage" mode=""></image>
		<image :src="codeSrc.templateImage" mode=""></image> -->
		<view class="login-body">
			<view class="title">Hi，Welcome Back！</view>
			<view class="title-login">
				输入您在无限轮回的账号
				<view style="color: #46a6f8" v-show="code" @click="showCode(2)">（密码登录）</view>
				<view style="color: #46a6f8" v-show="passWord" @click="showCode(1)">（验证码登录）</view>
			</view>
			<!-- 第一个输入框 -->
			<view class="">
				<u--input
					color="#ccc"
					type="number"
					customStyle="width: 610rpx;
					height: 94rpx;
					background: #211f30;
					box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0,0,0,0.15);
					border-radius: 14rpx;
					opacity:1;
					border: 2rpx solid #ccc;
					margin:0 34rpx 34rpx"
					border="surround"
					v-model="loginForm.phone"
					placeholder="请输入手机号"
				></u--input>
				<!-- 第二个输入框 -->
				<view class="code-box" v-show="code">
					<u--input
						color="#ccc"
						customStyle="width:610rpx;
						height: 94rpx;
						background: #211f30;
						box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0,0,0,0.15);
						border-radius: 14rpx;
						border: 2rpx solid #ccc;
						margin:0 21rpx 39rpx 34rpx"
						border="surround"
						placeholder="请输入图形码"
						v-model="imgcode"
					></u--input>
					<!-- <view class="code-class">获取验证码</view> -->
					<view class="login-btn-img">
						<image :src="codeUrl" @click="getCode"></image>
					</view>
				</view>
				<!-- 第三个输入框 -->
				<view class="code-box" v-show="code">
					<u--input
						color="#ccc"
						type="number"
						customStyle="width:610rpx;
						height: 94rpx;
						background: #211f30;
						box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0,0,0,0.15);
						border-radius: 14rpx;
						opacity:1;
						border: 2rpx solid #ccc;
						margin:0 21rpx 39rpx 34rpx"
						border="surround"
						v-model="loginForm.code"
						placeholder="请输入验证码"
					></u--input>
					<!-- <view class="code-class">获取验证码</view> -->
					<text v-if="phoneCodeStatus" @click="throttleConfirm" class="code-class">获取验证码</text>
					<span v-else class="code-class">重发({{ phoneCodeTime }}s)</span>
				</view>
				<!-- 第四个 -->
				<u--input
					color="#ccc"
					customStyle="width: 610rpx;
					height: 94rpx;
					background: #211f30;
					box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0,0,0,0.15);
					border-radius: 14rpx;
					opacity:1;
					border: 2rpx solid #ccc;
					margin:0 34rpx 34rpx"
					border="surround"
					placeholder="邀请码(选填)"
					v-show="code"
					v-model="loginForm.invite_code"
				></u--input>
				<!-- 密码登录 -->
				<view v-show="passWord">
					<u--input
						color="#ccc"
						customStyle="width:610rpx;
						height: 94rpx;
						background: #211f30;
						box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0,0,0,0.15);
						border-radius: 14rpx;
						opacity:1;
						border: 2rpx solid #ccc;
						margin:0 21rpx 39rpx 34rpx"
						border="surround"
						v-model="password"
						type="password"
						placeholder="请输入密码"
					></u--input>
				</view>
			</view>
			<!-- 登录按钮 -->
			<view class="login-btn" @click="handleLogin">登录</view>
			<view class="register-class">未注册用户验证后自动注册</view>
			<view class="usernotice-class" style="display: flex">
				<u--image
					v-show="!checked"
					@click="onchecked"
					width="26rpx"
					height="26rpx"
					radius="3rpx"
					style="position: absolute; margin-left: -35rpx"
					:src="imgUrl + '/static/newImage/nochecked.png'"
				></u--image>
				<u--image
					v-show="checked"
					@click="onchecked"
					width="26rpx"
					height="26rpx"
					radius="3rpx"
					style="position: absolute; margin-left: -35rpx"
					:src="imgUrl + '/static/newImage/checked.png'"
				></u--image>
				我已阅读并同意
				<text style="color: #46a6f8" @click="handleUserAgrement">《用户隐私协议》</text>
				和
				<text style="color: #46a6f8" @click="handlePrivacy">《服务协议》</text>
			</view>
		</view>
		<view class="notice-box">
			<view class="">Please establish a correct consumption concept for all users</view>
			<view class="">Reasonably evaluate one's own risk identification ability and risk bearing ability</view>
			<view class="">and participate rationally!</view>
		</view>
		<view class="uck">
			<u-link color="#787f8e" fontSize="10" href="https://beian.miit.gov.cn/#/Integrated/index" text="鄂ICP备2023024363号-1"></u-link>
		</view>
	</view>
</template>

<script>
import { getCodeImg, login, verification, loginByPassword, getInfo, dingLogin, dingLogin2 } from '@/api/login';
import CaptchaIndex from '@/components/Captcha/CaptchaIndex';
import { v4 as uuidv4 } from 'uuid';
import config from '@/config';
export default {
	components: {
		CaptchaIndex
	},
	data() {
		return {
			imgUrl: config.gillUrl,
			loginUrl: config.loginUrl,
			dingliangObj: {
				code: '',
				nickName: '',
				openId: '',
				phone: ''
			},
			dingliangLogin: true,
			loadShow: false,
			loading: false, //遮罩层
			codeUrl: '',
			captchaEnabled: true,
			// 用户注册开关
			register: false,
			globalConfig: getApp().globalData.config,
			value: false,
			loginForm: {
				phone: '',
				code: '',
				uuid: '',
				invite_code: ''
			},
			imgcode: '',
			password: '',
			uuid: '',
			type: 1,
			checked: false,
			passWord: false,
			code: true,
			show: false,
			phoneCodeStatus: true, //发送验证码状态
			phoneShow: false,
			phoneCodeTime: 60,
			args: '',
			throttling: false, // 初始时不处于节流状态
			vertify: false,
			codeSrc: ''
		};
	},
	onReady() {
		// 注意这里不能将一个组件赋值给data的一个变量，否则在微信小程序会
		// 造成循环引用而报错，如果你想这样做，请在onReady或者onLoad生命周期中定义，如下
		// this.refCode = this.$refs.uCode;
	},
	mounted() {},
	created() {
		if (process.env.UNI_PLATFORM === 'h5') {
			// 获取应用启动时的参数
			const launchOptions = uni.getLaunchOptionsSync();

			// 检查是否包含 inviteCode 参数
			if (launchOptions.query && launchOptions.query.inviteCode) {
				this.loginForm.invite_code = launchOptions.query.inviteCode;
			}
		}
		this.loadShow = true;
		this.getCode();
		// this.dingLogin(); //盯链登录i
		this.loadShow = false;
	},
	mounted() {
		this.loadShow = true;
	},
	onShow() {
		// 	var args = plus.runtime.arguments;
		// 	console.log(args, '参数');
		// 自定义函数解析 URL 查询参数
		// #ifdef APP-PLUS

		function parseQueryParams(queryString) {
			var params = {};
			var queries = queryString.substring(1).split('&');

			for (var i = 0; i < queries.length; i++) {
				var pair = queries[i].split('=');
				var key = decodeURIComponent(pair[0]);
				var value = decodeURIComponent(pair[1]);
				params[key] = value;
			}

			return params;
		}

		var args = plus.runtime.arguments;

		if (args) {
			// 获取参数字符串，假设它的格式是 "?code=xxx&state=xxx"
			var queryString = args.substring(args.indexOf('?'));

			// 使用自定义函数解析参数
			var queryParams = parseQueryParams(queryString);

			// 获取 code 和 state 参数的
			var code = queryParams['code'];
			var state = queryParams['state'];

			// console.log('Code:', code);
			// console.log('State:', state);
			if (code) {
				let params = {};
				params.state = state;
				params.code = code;
				this.dingLogin(params);
			}
		}
		// #endif
	},
	methods: {
		vertifyResult(vertify) {
			// console.log(vertify, '滑块验');
			this.vertify = vertify;
			if (this.vertify == true) {
			}
		},
		// 服务协议点击事件
		onchecked() {
			if (this.checked == false) {
				this.checked = true;
			} else if (this.checked == true) {
				this.checked = false;
			}
		},
		// 展示密码登录
		showCode(type) {
			if (type === 1) {
				this.code = true;
				this.passWord = false;
			} else if (type === 2) {
				this.code = false;
				this.passWord = true;
			}
			this.type = type;
		},
		//手机号验证
		validatorUser() {
			let phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
			if (this.loginForm.phone == '') {
				this.$modal.showToast('请输入您的手机号');
			} else if (!phoneReg.test(this.loginForm.phone)) {
				//电话校验
				this.$modal.showToast('手机号码格式不正确');
				// this.loginForm.phone = '';
			} else {
				this.showPopupCode();
			}
		},
		// 展示验证码弹框
		showPopupCode() {
			this.show = true;
		},
		// 倒计时
		startTime() {
			this.phoneCodeTime = 60;
			this.phoneCodeStatus = false;
			if (this.interval) {
				clearInterval(this.interval);
			}
			this.interval = setInterval(() => {
				// 使用箭头函数
				this.phoneCodeTime = this.phoneCodeTime - 1;
				if (this.phoneCodeTime < 1) {
					this.phoneCodeStatus = true;
					clearInterval(this.interval);
				}
			}, 1000);
		},
		closePopupCode() {
			this.show = false;
			this.imgcode = '';
		},
		// 假设你有一个名为 arrayBuffer 的 ArrayBuffer

		// 验证码的确认事件，节流事件，防止重复请求
		throttleConfirm() {
			if (!this.throttling) {
				// 如果没有处于节流状态，执行你的按钮点击逻辑
				this.validatorUser();
				this.confirmCode();
				// 设置节流状态为 true，并在一定时间后恢复为 false
				this.throttling = true;
				setTimeout(() => {
					this.throttling = false;
				}, 2000); // 1000毫秒（1秒）是节流的时间间隔，你可以根据需要调整
			}
		},
		// 获取图形验证码
		async getCode() {
			let uuid = uuidv4();
			const data = await getCodeImg(uuid);
			// console.log(data, '图片');
			// 将ArrayBuffer转换成Uint8Array
			const uint8Array = new Uint8Array(data);
			// 将Uint8Array转换成Base64
			const base64 = btoa(String.fromCharCode.apply(null, uint8Array));
			// 构建Data URL
			const dataUrl = `data:image/jpeg;base64,${base64}`;
			// 将Data URL 设置为图片的src属性
			this.codeUrl = dataUrl;
			this.loginForm.uuid = uuid;
			// console.log(this.codeUrl,"ppp")
		},
		// 检验图片验证码
		confirmCode() {
			this.loading = true;
			if (this.imgcode == '') {
				this.$modal.showToast('您还没有输入图形码');
			} else if (this.loginForm.phone != '' && this.imgcode != '') {
				verification(this.loginForm, this.imgcode).then((res) => {
					// console.log(res);
					if (res.code == 200) {
						this.show = false;
						this.startTime();
					} else {
						this.show = false;
						this.imgcode = '';
						this.$modal.showToast(res.msg);
					}
				});
				this.loading = false;
			} else {
				this.$modal.showToast('您还没有输入手机号');
			}
		},
		async handleLogin() {
			if (this.type == 1) {
				if (this.loginForm.phone == '') {
					this.$modal.showToast('您还没有输入手机号');
				} else if (this.loginForm.code === '') {
					this.$modal.showToast('请输入您的验证码');
				} else if (this.checked == false) {
					this.$modal.showToast('请同意用户协议');
				} else if (!this.dingliangLogin) {
					this.dingliangObj.phone = this.loginForm.phone;
					this.dingliangObj.code = this.loginForm.code;
					const res = await dingLogin2(this.dingliangObj);
					// console.log(res, ' dingLogin2(this.dingliangObj)');
					if (res.code == 200) {
						if (res.data.token) {
							//登录成功
							// this.setToken(res.data.token, res.data.tokenExpireTime);
							uni.setStorageSync('USER_TOKEN', res.data.token);
							this.getUserWithToken();
							console.log('跳转');
							uni.switchTab({
								url: '/pages/work/index'
							});
						}
					}
				} else {
					// this.$modal.loading('登录中，请耐心等待...');
					const data = this.loginForm;
					const res = await login(data);
					if (res.code == 200) {
						if (res.data.token) {
							//登录成功
							// this.setToken(res.data.token, res.data.tokenExpireTime);
							uni.setStorageSync('USER_TOKEN', res.data.token);
							this.getUserWithToken();
							uni.redirectTo({
								url: '/pages/webView/indexView?url=' + this.loginUrl
							});
							// this.$tab.reLaunch('/pages/webView/indexView?url=' + this.loginUrl);
						}
					}
				}
			} else if (this.type == 2) {
				if (this.loginForm.phone == '') {
					this.$modal.showToast('您还没有输入手机号');
				} else if (!this.password) {
					this.$modal.showToast('请输入密码');
					return true;
				} else if (this.checked == false) {
					this.$modal.showToast('请同意用户协议');
				} else {
					// this.$modal.loading('登录中，请耐心等待...');
					const res = await loginByPassword(this.loginForm.phone, this.password);
					// console.log(res, 'res');
					if (res.code == 200) {
						if (res.data.token) {
							uni.setStorageSync('USER_TOKEN', res.data.token);
							this.getUserWithToken();
							uni.redirectTo({
								url: '/pages/webView/indexView?url=' + this.loginUrl
							});
							// this.$tab.reLaunch('/pages/work/index');
						}
					}
				}
			}
		},
		// 获取提示
		async getUserWithToken() {
			const res = await getInfo();
			uni.setStorageSync('USER_ADMIN', res.data);
		},
		// 隐私协议
		handlePrivacy() {
			uni.navigateTo({
				url: '/pages/register?name=1'
			});
			// uni.reLaunch({
			// 	url:'/pages/AccountSecurity/setting/policy'
			// })
			// let site = this.globalConfig.appInfo.agreements[0];
			// this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`);
		},
		// 服务协议
		handleUserAgrement() {
			uni.navigateTo({
				url: '/pages/register'
			});
			// let site = this.globalConfig.appInfo.agreements[1];
			// this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`);
		}
	}
};
</script>

<style lang="scss">
.uck {
	height: 30rpx;
	margin-left: 32%;
	position: fixed;
	bottom: 0;
}
::v-deep .u-input {
	border: 1rpx solid #444 !important;
}
.login-page {
	width: 100%;
	height: 434rpx;
	padding-top: 275rpx;
	background-image: url('../static/newImage/login-bgi.png');
	background-size: 100% 100%;
	background-repeat: no-repeat;

	.login-body {
		width: 680rpx;
		height: 1030rpx;
		background: rgba(16, 10, 33, 0.8);
		box-shadow: 0rpx 3rpx 10rpx 3rpx rgba(15, 12, 23, 0.3);
		border-radius: 40rpx;
		opacity: 1;
		margin: auto;
		.title {
			padding: 73rpx 0 12rpx 49rpx;
			font-size: 42rpx;
			font-family: Trebuchet MS-Bold, Trebuchet MS;
			font-weight: bold;
			color: #ffffff;
		}

		.title-login {
			display: flex;
			font-size: 24rpx;
			font-family: Source Han Sans-Regular, Source Han Sans;
			font-weight: 400;
			color: #8a92a3;
			margin-left: 49rpx;
			margin-bottom: 71rpx;
		}

		.code-box {
			display: flex;
			width: 640rpx;

			.code-class {
				width: 256rpx;
				height: 90rpx;
				background: #211f30;
				box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0, 0, 0, 0.15);
				border-radius: 14rpx 14rpx 14rpx 14rpx;
				border: 2rpx solid #46a6f8;
				font-size: 28rpx;
				font-family: Source Han Sans-Medium, Source Han Sans;
				font-weight: 500;
				color: #46a6f8;
				line-height: 40rpx;
				text-align: center;
				line-height: 90rpx;
			}
		}

		.login-btn {
			width: 337rpx;
			height: 89rpx;
			background: linear-gradient(90deg, #3adfeb 0%, #4463ff 100%);
			box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0, 0, 0, 0.15);
			border-radius: 35rpx 35rpx 35rpx 35rpx;
			opacity: 1;
			font-size: 35rpx;
			font-family: Source Han Sans-Medium, Source Han Sans;
			font-weight: 500;
			color: #ffffff;
			line-height: 89rpx;
			text-align: center;
			margin-left: 170rpx;
			margin-bottom: 51rpx;
		}

		.register-class {
			width: 680rpx;
			height: 30rpx;
			font-size: 21rpx;
			font-family: Source Han Sans-Medium, Source Han Sans;
			font-weight: 500;
			color: #787f8e;
			line-height: 25rpx;
			text-align: center;
			margin-bottom: 40rpx;
		}

		.usernotice-class {
			width: 680rpx;
			height: 30rpx;
			font-size: 21rpx;
			font-family: Source Han Sans-Medium, Source Han Sans;
			font-weight: 500;
			color: #787f8e;
			line-height: 30rpx;
			text-align: center;
			margin-left: 125rpx;
		}
	}
}
.notice-box {
	width: 100%;
	height: 63rpx;
	font-size: 14rpx;
	font-family: Source Han Sans-Medium, Source Han Sans;
	font-weight: 500;
	color: #787f8e;
	margin-top: 60rpx;
	display: flex;
	align-items: center;
	flex-direction: column;
}
.login-btn-img {
	width: 256rpx;
	height: 90rpx;
	image {
		width: 256rpx;
		height: 90rpx;
		border-radius: 14rpx !important;
	}
}
</style>
